package org.vacoor.xqq.reply.impl.result;

import com.fasterxml.jackson.databind.JsonNode;
import org.vacoor.xqq.core.bean.Group;
import org.vacoor.xqq.reply.GroupListResolver;
import org.vacoor.xqq.reply.impl.JsonResolver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * {"retcode":0,"result":{"gnamelist":[{"flag":16777217,"name":"称","gid":2162237153,"code":1146484902}],"gmarklist":[{"uin":2162237153,"markname":"hehe"}], "gmasklist":[]}}
 */
public class SimpleGroupListResolver extends JsonResolver<List<Group>> implements GroupListResolver {

    @Override
    protected List<Group> doResolveResult(JsonNode result) {
        Map<Long, Group> groups = new HashMap<Long, Group>();
        JsonNode groupNames = result.get("gnamelist");
        if (groupNames != null && groupNames.isArray()) {
            for (JsonNode groupName : groupNames) {
                long gid = groupName.get("gid").asLong();
                String name = groupName.get("name").asText();
                long code = groupName.get("code").asLong(); // 获取群信息时需要
                Group group = createGroup(gid, name);
                group.setCode(code);
                groups.put(gid, group);
            }

            JsonNode gmarklist = result.get("gmarklist");
            if (gmarklist != null && gmarklist.isArray()) {
                for (JsonNode gmark : gmarklist) {
                    long gid = gmark.get("uin").asLong();
                    Group group = groups.get(gid);
                    if (group == null) {
                        continue;
                    }
                    group.setMark(gmark.get("markname").asText());
                }
            }
        }
        return new ArrayList<Group>(groups.values());
    }

    protected Group createGroup(long gid, String name) {
        return new Group(gid, name);
    }
}
